<!--帮助中心分类-->
<template>
    <div class="HelpCenterCategory">
      <div class="my_Select">
        <el-button class="bt-color-tjd" type="primary" style="margin: 10px 10px 10px 0;" @click="showParentDialog =
        true" :disabled="isButtonDisabled">添加父类</el-button>
        <el-button class="bt-color-tjd" type="primary" style="margin: 10px 0 10px 0;" @click="showSubclass = true" :disabled="isButtonDisabled">
          添加子类</el-button>
      </div>
<!--      <el-tabs  v-model="appTypeTab">-->
<!--        <el-tab-pane label="乐动健康生活" name="lefun_health"></el-tab-pane>-->
<!--        <el-tab-pane label="Yefit" name="ye_fit"></el-tab-pane>-->
<!--        <el-tab-pane label="Hi Yan" name="hi_yan"></el-tab-pane>-->
<!--      </el-tabs>-->
      <el-table :data="list" border style="width: 100%" v-loading="listLoading" row-key="uid"  default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column prop="appName" label="app名字" align="center"></el-table-column>
        <el-table-column prop="levelOneNameZh" label="分类名称" >
          <template v-slot="scope">
            <span>{{scope.row.type == 'top-level'? scope.row.levelOneNameZh : scope.row.levelTwoNameZh}}</span>
          </template>
        </el-table-column>
<!--        <el-table-column prop="levelOneNameEn" label="分类英文名" align="center">-->
<!--          <template v-slot="scope">-->
<!--            <div>{{scope.row.type == 'top-level'? scope.row.levelOneNameEn : scope.row.levelTwoNameEn}}</div>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column prop="nameZh" label="分类Banner" align="center" width="120">-->
<!--          <template v-slot="scope">-->
<!--            <div v-if="scope.row.advertResDOList">-->
<!--              <el-image v-for="(item, index) in scope.row.advertResDOList" :key="index" :src="item.appAdvertImgUrl" class="bannerImage"-->
<!--                      :preview-src-list="scope.row.bannerList" :initial-index="index">-->
<!--            </el-image>-->
<!--              &lt;!&ndash; <img :src="item.appAdvertImgUrl" class="bannerImage" v-for="(item, index) in scope.row.advertResDOList" :key="index"> &ndash;&gt;-->
<!--            </div>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column prop="pictureUrl" label="分类图标1" align="center" width="100">
          <template v-slot="scope">
            <img :src="scope.row.pictureUrl" v-if="scope.row.pictureUrl" class="icon-image">
          </template>
        </el-table-column>
        <el-table-column prop="count" label="专题数量" align="center"></el-table-column>
        <el-table-column label="是否启用"  align="center"  width="80">
          <template v-slot="scope">
            <el-tag type="success" v-if="scope.row.enabledState === '1'" size="small">启用</el-tag>
            <el-tag type="danger" v-else size="small">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="rank" label="分类排序" align="center" width="80"></el-table-column>
        <el-table-column prop="enabledState" label="分类等级" align="center" width="80">
          <template v-slot="scope">
            <div>{{ scope.row.type == 'top-level' ? '父类' : '子类' }}</div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200" align="center">
          <template v-slot="scope">
            <el-button  type="text" size="small" @click="setBanner(scope.row)" v-if="scope.row.type == 'top-level'">Banner设置</el-button>
            <el-button  type="text" size="small" @click="editCate(scope.row)">修改</el-button>
            <el-button  type="text" size="small" @click="deleteCate(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :title="parentForm.id ? '编辑父类' : '添加父类'" width="780px" :visible.sync="showParentDialog" center @close="parentClose">
        <el-form :model="parentForm" :rules="parentRules" label-position="left" label-width="100px" ref="parentForm" class="form" >
          <el-form-item label="App名字：" prop="appType">
            <el-select v-model="parentForm.appType" placeholder="请选择App名字" style="width: 30%;">
              <el-option
                  v-for="item in appTypeData"
                  :key="item.value"
                  :label="`${item.label}`"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分类名称" prop="nameZh">
            <el-input v-model="parentForm.nameZh" placeholder="请输入分类名称" size="small"></el-input>
          </el-form-item>
          <el-form-item label="分类英文名" prop="nameEn">
            <el-input v-model="parentForm.nameEn" placeholder="请输入分类英文名" size="small"></el-input>
          </el-form-item>
          <el-form-item label="排序">
            <el-input-number v-model="parentForm.index"  :min="0" size="small"></el-input-number>
          </el-form-item>
          <el-form-item label="是否显示">
            <el-switch v-model="parentForm.isShow" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="parentClose">取 消</el-button>
          <el-button  type="primary" @click="submitParent" :loading="parentSubmitLoading">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog :title="subclassForm.id? '编辑子类': '添加子类'" width="780px" :visible.sync="showSubclass" center @close="subClassClose">
        <el-form :model="subclassForm" :rules="subclassRules" label-position="left" ref="subclassForm" label-width="100px" class="form">
          <el-form-item label="父级分类" prop="parent">
            <el-select v-model="subclassForm.parent" placeholder="请选择父级分类" size="small" style="width: 100%;">
              <el-option v-for="item in list" :key="item.id"
                         :label="`${item.appName}-${item.levelOneNameZh}(${item.levelOneNameEn})`"
                         :value="item.helpCode"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分类名称" prop="nameZh">
            <el-input v-model="subclassForm.nameZh" placeholder="请输入分类名称" size="small"></el-input>
          </el-form-item>
          <el-form-item label="分类英文名" prop="nameEn">
            <el-input v-model="subclassForm.nameEn" placeholder="请输入分类英文名" size="small"></el-input>
          </el-form-item>
          <el-form-item label="分类图标" prop="icon">
            <upLoads :url="subclassForm.icon" @chang_up="file => subclassForm.icon = file.src"></upLoads>
          </el-form-item>
          <el-form-item label="分类排序">
            <el-input-number v-model="subclassForm.index"  :min="0" size="small"></el-input-number>
          </el-form-item>
          <el-table-column label="是否启用"  align="center"  width="80">
            <template v-slot="scope">
              <el-tag type="success" v-if="scope.row.isShow === 1" size="small">启用</el-tag>
              <el-tag type="danger" v-else size="small">禁用</el-tag>
            </template>
          </el-table-column>
<!--          <el-form-item label="是否显示">-->
<!--            <el-switch v-model="subclassForm.isShow" active-color="#13ce66" inactive-color="#ff4949"  :active-value="1" :inactive-value="0"></el-switch>-->
<!--          </el-form-item>-->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="subClassClose">取 消</el-button>
          <el-button  type="primary" @click="submitSubClass" :loading="subClassSubmitLoading">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="Banner设置" width="950px" :visible.sync="banner.show" center @close="closeBanner" class="bannerDialog">
        <el-button size="small" @click="addBannerItem"> 添  加 </el-button>
        <el-table border style="width: 100%;margin-top: 10px;" size="small" :data="banner.list">
          <el-table-column prop="code" label="图片" align="center">
            <template v-slot="scope">
              <div class="hello">
                <div class="show-img" v-if="scope.row.imageUrl">
                  <img :src="scope.row.imageUrl" style="width: 100%;height: auto;"/>
                </div>
                <div class="upload_img" v-else >
                  <div class="up">上传图片</div>
                </div>
                <div class="upload">
                  <input  type="file" accept=".jpg, .png, .bmp, .jpeg" @change="fileChange($event, scope.$index)" />
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="关联类型" align="center">
            <template v-slot="scope">
              <el-radio-group v-model="scope.row.type">
                <el-radio :label="1">文章</el-radio>
                <el-radio :label="2">分类</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="关联链接" align="center">
            <template v-slot="scope">
              <el-select v-model="scope.row.advertCode" placeholder="请选择" size="small" filterable v-if="scope.row.type == 1">
                <el-option v-for="(item, index) in banner.articleList" :key="index" :label="item.levelThreeNameZh" :value="item.code"></el-option>
              </el-select>
              <el-select v-model="scope.row.remark" placeholder="请选择" size="small" filterable v-if="scope.row.type == 2">
                <el-option v-for="(item, index) in banner.secondaryList" :key="index" :label="item.levelTwoNameZh" :value="item.levelTwoCode"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="是否显示" align="center" width="120">
            <template v-slot="scope">
              <el-switch v-model="scope.row.effectiveStatus" active-color="#13ce66" inactive-color="#ff4949"  :active-value="0" :inactive-value="1"></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="排序" align="center">
            <template v-slot="scope">
              <el-input-number v-model="scope.row.rank"  :min="0" size="small"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template v-slot="scope">
              <el-button type="text" @click="deleteBanner(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeBanner">取 消</el-button>
          <el-button  type="primary" @click="submitBanner" :loading="banner.loading">确 定</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import { post } from '@/api/my_axios'
export default {
  data () {
    return {
      isButtonDisabled: true, // 添加禁用按钮
      listLoading: false,
      showParentDialog: false,
      parentSubmitLoading: false,
      showSubclass: false,
      subClassSubmitLoading: false,
      appTypeTab: 'lefun_health',
      appType: 'lefun_health',
      dataType: 0,
      parentForm: {
        nameZh: '',
        nameEn: '',
        isShow: 1,
        index: 1,
        appType: ''
      },
      parentRules: {
        appType: [{ required: true, message: '请选择App', trigger: 'blur' }],
        nameZh: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
        nameEn: [{ required: true, message: '请输入分类英文名', trigger: 'blur' }]
      },
      subclassForm: {
        nameZh: '',
        nameEn: '',
        parent: '',
        icon: '',
        index: 1,
        isShow: 1,
        id: ''
      },
      banner: {
        show: false,
        loading: false,
        id: '',
        name: '',
        list: [],
        articleList: [],
        secondaryList: []
      },
      subclassRules: {
        nameZh: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
        nameEn: [{ required: true, message: '请输入分类英文名', trigger: 'blur' }],
        parent: [{ required: true, message: '请选择父级分类', trigger: 'change' }],
        icon: [{ required: true, message: '请上传分类图标', trigger: 'change' }]
      },
      appTypeData: [
        { value: 'lefun_health', label: '乐动健康生活' },
        { value: 'ye_fit', label: 'Yefit' },
        { value: 'hi_yan', label: 'Hi Yan' }
      ]
    }
  },

  mounted () {
    this.getList()
    this.getArticle()
  },

  watch: {
    // 标签切换
    appTypeTab () {
      this.appType = this.appTypeTab
      this.pageNum = 1
      this.getList()
      this.getArticle()
    }
  },

  methods: {

    // 父类dialog清空
    parentClose () {
      this.parentForm = {
        appType: '',
        nameZh: '',
        nameEn: '',
        isShow: 1,
        index: 1,
        id: ''
      }
      this.$refs.parentForm.resetFields()
      this.showParentDialog = false
    },
    // 提交父类保存
    submitParent () {
      this.$refs.parentForm.validate(valid => {
        if (!valid) return false
        this.parentSubmitLoading = true
        const data = this.parentForm
        const params = {
          appType: data.appType,
          enabledState: data.isShow,
          levelOneNameEn: data.nameEn,
          levelOneNameZh:
          data.nameZh,
          rank: data.index,
          remark: ''
        }
        if (data.id) params.id = data.id
        post('/api/cms/sysuser/auth/systemApp/help/center/saveHelpCenterInfo', params).then(res => {
          if (res.code === 200) {
            this.$message({ message: '保存成功', type: 'success' })
            this.parentClose()
            this.getList()
            this.getArticle()
          } else {
            this.$message({ message: res.msg, type: 'error' })
          }
        }).finally(() => {
          this.parentSubmitLoading = false
        })
      })
    },
    // 获取列表信息
    getList () {
      this.isButtonDisabled = true
      this.listLoading = true
      const params = { pageNum: 1, pageSize: 20, appType: this.appType, dataType: this.dataType }
      Promise.all([post('api/cms/sysuser/auth/systemApp/help/center/queryHelpCenterList', params),
        post('/api/cms/sysuser/auth/systemApp/help/center/getTitleCascadeRelation', params)]).then(res => {
        const topList = res[0].data
        const allList = res[1].data
        const appName = this.appTypeData.find(v => v.value === this.appType).label
        topList.forEach(item => {
          item.type = 'top-level'
          if (item.advertResDOList) {
            item.bannerList = item.advertResDOList.map(x => {
              return x.appAdvertImgUrl
            })
          }
          item.uid = this.generateRandomNumber()
          const children = allList.filter(x => x.helpCode === item.helpCode)
          let count = 0
          if (children.length) {
            children[0].twoLevelVOList.forEach(ele => {
              ele.uid = this.generateRandomNumber()
              ele.parent = item.helpCode
              count += ele.count
            })
            item.children = children[0].twoLevelVOList
          }
          item.count = count
          item.appName = appName
        })
        this.list = topList
      }).finally(() => {
        this.isButtonDisabled = false
        this.listLoading = false
      })
    },
    generateRandomNumber () {
      var timestamp = new Date().getTime() // 获取当前时间戳
      var randomNumber = Math.floor(Math.random() * 1000000000) // 生成一个0到999999999之间的随机数
      var result = timestamp.toString() + randomNumber.toString() // 将时间戳和随机数拼接成字符串
      return result.substr(result.length - 10)
    },
    // 删除分类
    deleteCate (item) {
      this.$confirm('确认删除此分类?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const request = item.type === 'top-level' ? post('/api/cms/sysuser/auth/systemApp/help/center/deleteById', Number(item.id)) : post('/api/cms/sysuser/auth/systemApp/help/center/deleteDetailByIds', { addSubclass: true, id: Number(item.id), levelTwoCode: item.levelTwoCode })
        // /api/cms/sysuser/auth/systemApp/help/center/deleteDetailByIds
        request.then(res => {
          if (res.code === 200) {
            this.$message({ message: '删除成功', type: 'success' })
            this.getList()
            this.getArticle()
          }
        })
      })
    },
    // 编辑分类
    editCate (item) {
      if (item.type === 'top-level') {
        this.parentForm = {
          appType: item.appType,
          nameZh: item.levelOneNameZh,
          nameEn: item.levelOneNameEn,
          isShow: Number(item.enabledState),
          index: item.rank,
          id: item.id
        }
        this.showParentDialog = true
      } else {
        this.subclassForm = {
          appType: item.appType,
          nameZh: item.levelTwoNameZh,
          nameEn: item.levelTwoNameEn,
          parent: item.parent,
          icon: item.pictureUrl,
          index: item.rank,
          isShow: Number(item.enabledState),
          id: item.id,
          levelTwoCode: item.levelTwoCode
        }
        this.showSubclass = true
      }
    },
    // 子类dialog清空
    subClassClose () {
      this.subclassForm = { nameZh: '', nameEn: '', parent: '', icon: '', index: 1, isShow: 1, id: '' }
      this.$refs.subclassForm.resetFields()
      this.showSubclass = false
    },
    // 子类提交保存
    submitSubClass () {
      this.$refs.subclassForm.validate(valid => {
        if (!valid) return false
        this.subClassSubmitLoading = true
        const data = this.subclassForm
        const params = { addSubclass: true, helpCode: data.parent, levelTwoNameEn: data.nameEn, levelTwoNameZh: data.nameZh, pictureSrc: data.icon, rank: data.index, enabledState: data.isShow }
        if (data.id) {
          params.id = data.id
          params.levelTwoCode = data.levelTwoCode
          if (params.pictureSrc.indexOf('http') !== -1) delete params.pictureSrc
        }
        params.appType = this.appType
        params.dataType = this.dataType
        post('/api/cms/sysuser/auth/systemApp/help/center/saveHelpCenterDetailInfo', params).then(res => {
          if (res.code === 200) {
            this.$message({ message: '保存成功', type: 'success' })
          } else {
            this.$message({ message: res.msg, type: 'error' })
          }
        }).finally(() => {
          this.subClassClose()
          this.getList()
          this.getArticle()
          this.subClassSubmitLoading = false
        })
      })
    },
    // banner设置
    setBanner (item) {
      this.banner.show = true
      this.banner.id = item.appAdvertId
      this.banner.name = item.levelOneNameZh
      this.banner.secondaryList = item.children
      if (item.advertResDOList) {
        const bannerList = JSON.parse(JSON.stringify(item.advertResDOList))
        bannerList.forEach(ele => {
          ele.effectiveStatus = Number(ele.effectiveStatus)
          ele.imageUrl = ele.appAdvertImgUrl
          const advert = this.banner.articleList.filter(x => x.contentZh === ele.appAdvertHtmlUrl)
          if (advert && advert.length) {
            ele.advertCode = advert[0].code
            ele.type = 1
          } else if (ele.remark) {
            ele.type = 2
          }
        })
        this.banner.list = bannerList
      }
    },
    // 图片上传处理
    fileChange (el, index) {
      if (!el.target.files[0].size) return
      const files = el.target.files
      for (let i = 0; i < files.length; i++) {
        if (files[i].type !== '') {
          this.fileAdd(files[i], index)
        } else {
          this.folders(el.target.items[i], index)
        }
      }
      el.target.value = ''
    },
    // 文件夹处理
    folders (files, index) {
      if (files.kind) files = files.webkitGetAsEntry()
      files.createReader().readEntries(file => {
        for (let i = 0; i < file.length; i++) {
          if (file[i].isFile) {
            this.foldersAdd(file[i], index)
          } else {
            this.folders(file[i], index)
          }
        }
      })
    },
    foldersAdd (entry, index) {
      entry.file(file => {
        this.fileAdd(file, index)
      })
    },
    fileAdd (file, index) {
      const _this = this
      const reader = new FileReader()
      reader.vue = this
      reader.readAsDataURL(file)
      reader.onload = function () {
        file.src = this.result
        _this.uploadBanner(file, index)
      }
    },
    // banner图片上传
    uploadBanner (file, index) {
      this.banner.list[index].imageName = file.name
      this.banner.list[index].imageUrl = file.src
    },
    // 增加banner条数
    addBannerItem () {
      this.banner.list.push({ appAdvertId: this.banner.id, advertCode: '', effectiveStatus: 0, imageName: '', imageUrl: '', rank: 1, appAdvertHtmlUrl: '', appAdvertHtmlUrlEn: '', type: 1 })
    },
    // 获取文章列表
    getArticle () {
      const params = { appType: this.appType, dataType: this.dataType }
      post('/api/cms/sysuser/auth/systemApp/help/center/queryThreeTitleList', params).then(res => {
        this.banner.articleList = res.data
      })
    },
    // 删除文章
    deleteBanner (scope) {
      this.$confirm('确认删除此Banner?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.banner.list.splice(scope.$index, 1)
      })
    },
    closeBanner () {
      this.banner.list = []
      this.banner.show = false
    },
    // 保存banner
    submitBanner () {
      const params = []
      let imageFlag = false
      this.banner.list.forEach((item, index) => {
        const obj = { appAdvertId: item.appAdvertId, appAdvertTitle: `帮助中心-${this.banner.name}-banner(${index + 1})`, effectiveStatus: item.effectiveStatus, rank: item.rank, imageName: item.imageName, imageUrl: item.imageUrl }
        if (item.appAdvertResId) obj.appAdvertResId = item.appAdvertResId
        if (!item.imageUrl) imageFlag = true
        if (item.type === 1 && item.advertCode) {
          const article = this.banner.articleList.filter(x => x.code === item.advertCode)
          obj.appAdvertHtmlUrl = article[0].contentZh
          obj.appAdvertHtmlUrlEn = article[0].contentEn
          obj.remark = ''
        }
        if (item.type === 2 && item.remark) {
          obj.remark = item.remark
          obj.appAdvertHtmlUrl = ''
          obj.appAdvertHtmlUrlEn = ''
        }
        if (item.imageUrl.indexOf('http') !== -1) delete obj.imageUrl
        params.push(obj)
      })
      if (imageFlag) {
        this.$message.error('请上传Banner图片')
        return false
      }
      this.banner.loading = true
      post('/api/cms/sysuser/auth/systemApp/help/center/saveAppBannerInfo', { saveResDTOList: params }).then(res => {
        if (res.code === 200) {
          this.$message({ message: '保存成功', type: 'success' })
          this.closeBanner()
          this.getList()
          this.getArticle()
        } else {
          this.$message({ message: res.msg, type: 'error' })
        }
      }).finally(() => {
        this.banner.loading = false
      })
    }
  }
}
</script>

<style scoped lang="scss">
.HelpCenterCategory {
  padding: 56px 20px 140px 20px;
}
.icon-image{
  width: 62px;
  height: 62px;
  object-fit: cover;
}
.bannerImage{
  width: 100px;
  height: auto;
  margin-bottom: 4px;
  display: block;
}
.bannerDialog .hello{
  width: 100px;
  margin: 0 auto;
  position: relative;
  cursor: pointer;
}
.bannerDialog .upload_img {
  position: relative;
  width: 100px;
  height: 100px;
  line-height: 100px;
  border: 1px solid #999;
  overflow: hidden;
  cursor: pointer;
  border-radius: 6px;
}
.bannerDialog .show-img {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
}

.bannerDialog .up {
    position: absolute;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.bannerDialog .upload_img:hover .delet {
  position: absolute;
  top: 0;
  left: 0;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.4);
}

.bannerDialog .upload_img img {
  height: 100px;
}
.bannerDialog .upload{
  width: 100px;
  height: 100px;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
}
.bannerDialog .upload input{
  width: 100%;
  height: 100%;
}
</style>
